package net.lesscoding.producer;

import net.lesscoding.common.Const;
import net.lesscoding.listener.ICBCTransactionListener;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.TransactionMQProducer;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.common.message.Message;

import java.util.concurrent.*;

/**
 * @author eleven
 * @date 2024/5/30 21:37
 * @apiNote
 */
public class TransactionProducer {
    public static void main(String[] args) throws MQClientException {
        TransactionMQProducer producer = new TransactionMQProducer("tpg");
        producer.setNamesrvAddr(Const.TS_NAME_SRV_ADDR_OS1);

        /**
         * @param corePoolSize:     线程池中核心线程的数量
         * @param maximumPoolNum：   线程池最大线程数
         * @param keepAliveTime：    存活时间
         * @param unit：             存活时间的单位
         * @param workQueue：        临时存放任务的队列，参数就是队列的长度
         * @param threadFactory：    线程工厂
         */
        ExecutorService executorService = new ThreadPoolExecutor(2, 5, 100, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(5), new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setName("client-transaction-msg-check-thread");
                return thread;
            }
        });

        producer.setExecutorService(executorService);
        // 添加事务监听器
        producer.setTransactionListener(new ICBCTransactionListener());
        producer.setSendMsgTimeout(10000);
        producer.start();

        String[] tags = {"TAG-A", "TAG-B", "TAG-C"};

        for (int i = 0; i < 3; i++) {
            byte[] body = ("Hi," + i).getBytes();
            Message msg = new Message("someTopic", tags[i], body);
            // 发送事务消息
            // 第二个参数用于指定在执行本地事务是需要使用的自定义业务参数
            TransactionSendResult sendResult = producer.sendMessageInTransaction(msg, null);
            System.out.println("发送结果" + sendResult.getSendStatus());
        }
    }
}
